package screen;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import ctrl.MyConnectionFactory;

/**
 * 弹出窗口显示用户大头像图片
 * @author Walkline
 *
 */
public class ShowUserAvatarImageScreen extends PopupScreen
{
	byte[] avatarData=null;
	Thread thread=null;
	String _avatarUrl="";
	BitmapField bitmapField;
	
	/**
	 * 弹出窗口显示用户大头像图片
	 * @param avatarUrl 大头像图片URL，取自用户信息
	 */
	public ShowUserAvatarImageScreen(String avatarUrl)
	{
		super(new VerticalFieldManager());
		
		_avatarUrl=avatarUrl;
		
		bitmapField=new BitmapField(Bitmap.getBitmapResource("avatar_large.png"));
		
		add(bitmapField);

		Thread thread=new Thread() 
		{
			public void run()
			{
                MyConnectionFactory factory=new MyConnectionFactory();
                ConnectionDescriptor descriptor=factory.getConnection(_avatarUrl);
                if(descriptor==null) {return;}
                
                HttpConnection httpConnection=(HttpConnection) descriptor.getConnection();
                InputStream inputStream=null;
                
				try {
					inputStream=httpConnection.openInputStream();

					if(inputStream.available()>0)
					{
						avatarData=IOUtilities.streamToBytes(inputStream);

						if(avatarData.length==httpConnection.getLength())
						{
							bitmapField.setBitmap(Bitmap.createBitmapFromBytes(avatarData, 0, -1, 1));							
						}
					}
				} catch (IOException e) {}
			}
		};
		thread.start();
	}
	
	public boolean onClose()
	{
		if(thread!=null) {try {thread=null;} catch (Exception e) {}}
		
		try {UiApplication.getUiApplication().popScreen(this);} catch (Exception e) {}
		
		return true;
	}
	
	protected boolean keyChar(char key, int status, int time)
	{
		if(key==Characters.ESCAPE)
		{
			onClose();
			
			return true;
		}
		
		return super.keyChar(key, status, time);
	}
}